package com.example.apiversioncontroldemo.util.vcon;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chen.cr
 * @since 2023/10/19
 */
@Slf4j
public class RequestUtils {
    /**
     * 匹配url中包含 'v1/'
     */
    private static final Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)/");


    public static Integer findApiVersion(HttpServletRequest request) {
        try {
            String uri = request.getRequestURI();
            Matcher matcher = VERSION_PREFIX_PATTERN.matcher(uri);
            if (matcher.find()) {
                String group = matcher.group(1);
                return Integer.parseInt(group);
            }
        } catch (Exception e) {
            log.info("api 版本转换异常:" + request.getRequestURI());
        }
        return null;
    }
}
